package com.qianbei.common.web;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.AttributeSet;
import com.tencent.smtt.sdk.CookieManager;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import android.widget.FrameLayout;

import com.qianbei.common.init.SystemConfig;
import com.qianbei.common.net.view.ProgressView;
import com.qianbei.user.login.LoginWxActivity;

import java.net.URLEncoder;

public class MyWebView extends FrameLayout {

	public WebView webView;
	
	public ProgressView upDialog;

	
	private boolean isError;
	private Context context;
	private String  mUrl;
	
	  CookieManager manager ;
	public MyWebView(final Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context =context;
		webView = new WebView(context);
		
		this.addView(webView, LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);
		upDialog = new ProgressView(context);// .showProgress("正在上传");
		initWebView();
		
		this.addView(upDialog, LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);
	}

	public MyWebView(Context context) {
		this(context, null);
	}

	@SuppressLint("SetJavaScriptEnabled")
	public void initWebView() {
		WebSettings ws = webView.getSettings();
		ws.setJavaScriptEnabled(true);
		ws.setCacheMode(WebSettings.LOAD_NO_CACHE);
		ws.setAllowFileAccess(true);
		ws.setAppCacheEnabled(true);
		ws.setDomStorageEnabled(true);
		ws.setDatabaseEnabled(true);
		
		webView.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onReceivedTitle(WebView view, String title) {
				if (webListener != null) {
					webListener.loadTitle(title);
				}
			}

		});
		
		webView.setWebViewClient(new WebViewClient() {
			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				isError = true;
//				webListener.pageError();
				upDialog.showError();
			}

			@Override
			public void onPageFinished(WebView view, String url) {

				// 清除缓存
				if (!isError) {
					
					upDialog.progressFinish();
//					webListener.pageFinished();
				}

				if (url.endsWith("?status=open")){
					((Activity)context).startActivityForResult(new Intent(context, LoginWxActivity.class),1);
					webView.goBack();
				}else{
					mUrl = url;
				}
			}

		});
	}

	public void loadUrl(String url) {
		mUrl =url;
		synCookies(context,".jiemian.com");
		webView.loadUrl(url);
		upDialog.showProgress(null);
	}

	/**
	 * 加载富文本
	 * 
	 * @param data
	 */
	public void loadNativyData(String data) {
		webView.loadData(fmtString(data), "text/html", "utf-8");
	}

	private String fmtString(String str) {
		String notice = "";
		try {
			notice = URLEncoder.encode(str, "utf-8");
		} catch (Exception ex) {
		}
		return notice;
	}

	public interface MyWebViewListener {
		// 加载页面标题
		public void loadTitle(String title);
		
//		public void pageFinished();

//		public void pageError();
	}

	public MyWebViewListener webListener;
	
	
	/** 
	 * 同步一下cookie 
	 */  
	public  void synCookies(Context context, String url) {  
		CookieSyncManager.createInstance(context);
		CookieManager cookieManager = CookieManager.getInstance();
		cookieManager.setAcceptCookie(true);
		cookieManager.removeSessionCookie();// 移除
		cookieManager.removeAllCookie();

		String[] cookieArray = SystemConfig.getInstance().getCooke().split(";");

		for (int i = 0; i < cookieArray.length; i++) {
			if (cookieArray[i].startsWith("Domain=")
					|| cookieArray[i].startsWith("Path=")) {
				continue;
			}

			cookieManager.setCookie(".jiemian.com", cookieArray[i]
					+ ";Domain=.jiemian.com" + ";Path=/");
		}

		CookieSyncManager.getInstance().sync();
	}

	public void refreshWebView(){
		loadUrl(mUrl);
	}
}
